package com.news.news.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * Created by 罗铠威 on 2023/8/30 7:56
 * type:
 */
public class UserTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        String token = request.getHeader("userToken");//【这个就是那个自定义的请求头】
//        System.out.println("admintoken已接收:" + token);
        //验证token代码是否有效--
//【verify()方法是验证token是否是伪造的、失效的，返回一个布尔类型的值】
        boolean res = JWTUtil.tokenVerify(token);//false-token【失效or伪造的】
        CommonResult commonResult = null;
        if (!res) {
            commonResult = new CommonResult(202, res, "token已经失效或伪造！");
            PrintWriter responds = response.getWriter();
            responds.print(new ObjectMapper().writeValueAsString(commonResult));//发送json格式的信息至前端
        }
        return res;
    }
}
